package org.social.plugin;

import java.io.File;
import java.nio.charset.Charset;

import org.social.constant.SocialConstant;

import com.jfinal.plugin.IPlugin;
import com.sojoys.artifact.manager.PropManager;
import com.xiaoleilu.hutool.crypto.SecureUtil;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import com.xiaoleilu.hutool.setting.Setting;

/**
 * @author : DengYing
 * @CreateDate : 2017年4月28日 上午12:04:53
 * @Description ：CSV校验插件
 */
public class VerifyCsvPlugin implements IPlugin {
	
	static final Log log = LogFactory.get(VerifyCsvPlugin.class);
	static final String CSV_DIR = VerifyCsvPlugin.class.getClassLoader().getResource("").getPath() + "gameConfig/";
	
	@Override
	public boolean start() {
		
		File file = new File(CSV_DIR);
		if (!file.exists() || !file.isDirectory()) {
			file.mkdirs();
		}
		
		String url = PropManager.get(SocialConstant.DOWNLOAD_CSV_URL);
		String verifyFileName = PropManager.get(SocialConstant.DOWNLOAD_CSV_MD5);
		
		long contentSize = HttpUtil.downloadFile(url + verifyFileName, CSV_DIR);
		if (contentSize > 0) {
			// 读取下载的校验文件
			Setting setting = new Setting(new File(CSV_DIR + verifyFileName),Charset.forName("UTF-8"),false);
			setting.forEach((k,v) -> {
				String fielName = k.toString();
				if(FileUtil.exist(CSV_DIR + fielName)){
					String content = FileUtil.readString(CSV_DIR + fielName, "UTF-8");	
					String md5 = SecureUtil.md5(content);
					// 文件没有变动
					if (v.equals(md5)) {
						return;
					}
				}
				HttpUtil.downloadFile(url + fielName, CSV_DIR);
			});
		}else {
			log.warn("csv verify file size = {}",contentSize);
		}
		
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}

	
	public static void main(String[] args) {
//		PropManager.use("app.properties");
//
//		String verifyFileName = PropManager.get(GameConstant.DOWNLOAD_CSV_MD5);
//
//		String url = "D:/Work/SVN/dal/config/develop/";
//
//		List<File> csvs = FileUtil.loopFiles(url, new FileFilter() {
//			@Override
//			public boolean accept(File pathname) {
//				return FileUtil.pathEndsWith(pathname, "csv");
//			}
//		});
//
//		List<String> list = Lists.newArrayList();
//		list.add("# Date:" + DateUtil.now() + " Count:"+csvs.size());
//		for (File file : csvs) {
//			String val = file.getName() + "=" + SecureUtil.md5(FileUtil.readString(file, "UTF-8"));
//			list.add(val);
//		}
//		FileUtil.writeLines(list, url + verifyFileName, "UTF-8");
		
//		PropManager.use("app.properties");
//		new VerifyCsvPlugin().start();
	}
}
